﻿#include "Timer.h"

#define TIMEOUT 100

namespace LH
{
	TimerThread::TimerThread()
	{
		//std::thread t{ [this]() {run(); } };
		//m_thread.swap(t);
		m_thread = std::thread{ [this]() {run(); } };
	}

	TimerThread::~TimerThread()
	{
		m_quit.store(true);
		if (m_thread.joinable()) {
			m_thread.join();
		}
	}

	void TimerThread::run()
	{
		m_quit.store(false);
		while (!m_quit.load())
		{
			// 当前时间点
			auto tp = std::chrono::steady_clock::now();
			// 执行当前定时器任务
			if (this->fireTimer(tp))
			{
				// 更新时间点
				tp = std::chrono::steady_clock::now();
			}
			// 计算超时
			auto timeout = calculateTimeout(tp);
			if (timeout == -1 || timeout > TIMEOUT) timeout = TIMEOUT;

			// windows上sleep休眠精度不够，需要利用系统API进行相关操作
			// 条件变量wait_for效果比 std::this_thread::sleep_for效果好。但是仍然存在误差
			std::unique_lock<std::mutex> lock(m_mutex);
			m_cv.wait_until(lock, (tp + std::chrono::milliseconds{timeout}));
			// std::this_thread::sleep_for(std::chrono::milliseconds{ timeout });
		}
	}
}
